import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {environment} from '../../../environments/environment';
import {SystemRes} from '../base.model';
import {BaseService} from '../base.service';
import {CommonTool} from '../../common/common.tool';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'app-forget',
  templateUrl: './forget.component.html',

  styleUrls: ['./forget.component.css']
})
export class ForgetComponent implements OnInit {
  validateForm: FormGroup;
  public system: SystemRes;
  public systemInfoMap: any;
  public countdown: any;
  public isCaptcha: boolean;

  constructor(private fb: FormBuilder,
              public baseService: BaseService,
              private commonTool: CommonTool,
              private router: Router,
              private message: NzMessageService) {
    this.system = JSON.parse(sessionStorage.getItem(environment.systemInfo));
    this.systemInfoMap = {};
    for (const systemInfo of this.system.systemInfoList) {
      this.systemInfoMap[systemInfo.code] = systemInfo.value;
    }
    this.countdown = 60;
    this.isCaptcha = true;
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      account: [null, [Validators.email, Validators.required]],
      password: [null, [Validators.required, Validators.minLength(6)]],
      checkPassword: [null, [Validators.required, this.confirmationValidator]],
      captcha: [null, [Validators.required]]
    });
  }

  /**
   * 失去焦点事件
   */
  public verifyAccount() {
    if (this.validateForm.controls.account.status === 'VALID') {
      this.baseService.verifyAccount({account: this.validateForm.controls.account.value}).subscribe((res) => {
        this.validateForm.controls['account'].setValidators(
          [Validators.email, Validators.required, function (control: FormControl) {
            if (!control.value) {
              return {required: true};
            } else if (!res.accountCorrect) {
              return {confirm: true};
            }
            return {};
          }]);
        this.validateForm.controls.account.markAsDirty();
        this.validateForm.controls.account.updateValueAndValidity();
      });
    }
  }

  /**
   * 输入事件
   */
  public keydown() {
    this.validateForm.controls['account'].setValidators([Validators.email, Validators.required]);
    this.validateForm.controls.account.markAsDirty();
    this.validateForm.controls.account.updateValueAndValidity();
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.status === 'VALID') {
      const form = this.validateForm.getRawValue();
      this.baseService.forget({
        account: form.account,
        password: form.password,
        mailCode: form.captcha
      }).subscribe(() => {
        this.message.success('找回密码成功！');
        this.router.navigate(['/login']);
      });
    }
  }

  /**
   * 验证密码是否相等
   */
  public confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    } else if (control.value !== this.validateForm.controls.password.value) {
      return {confirm: true, error: true};
    }
    return {};
  };

  /**
   * 获取验证码
   */
  getCaptcha(): void {
    const $this = this;
    this.validateForm.controls.account.markAsDirty();
    this.validateForm.controls.account.updateValueAndValidity();
    if (this.validateForm.controls.account.status === 'VALID') {
      if (this.isCaptcha) {
        this.isCaptcha = false;
        this.baseService.sendMailVerifyCode({
          type: 'forget',
          mailbox: this.validateForm.getRawValue().account
        }).subscribe(res => {
          const interval = setInterval(function () {
            $this.countdown--;
            if ($this.countdown <= 0) {
              $this.isCaptcha = true;
              $this.countdown = 0;
              clearInterval(interval);
            }
          }, 1000);
        });
      }
    }
  }
}
